﻿using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using SmartParking.IService;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace SmartParking.ViewModels
{
    public class LoginViewModel : BindableBase, IDialogAware
    {


        public string Title => "用户登录";
        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {

        }

        private string _userName = "admin";

        public string UserName
        {
            get { return _userName; }
            set { ErrorInfo = ""; SetProperty<string>(ref _userName, value); }
        }

        // 设置默认值用来触发OnPropertyChanged事件
        private string _password = "123456";

        public string Password
        {
            get { return _password; }
            set { ErrorInfo = ""; SetProperty<string>(ref _password, value); }
        }

        private bool _isRecord;

        public bool IsRecord
        {
            get { return _isRecord; }
            set { SetProperty<bool>(ref _isRecord, value); }
        }

        public DelegateCommand LoginCommand { get; set; }

        IUserService _userService;
        public LoginViewModel(IUserService userService)
        {
            _userService = userService;
            LoginCommand = new DelegateCommand(DoLogin);
        }

        private string _errorInfo;

        public string ErrorInfo
        {
            get { return _errorInfo; }
            set { SetProperty<string>(ref _errorInfo, value); }
        }


        private void DoLogin()
        {
            try
            {
                ErrorInfo = "";
                var user = _userService.Login(this.UserName, this.Password);
                if (user == null)
                {
                    ErrorInfo = "用户名或密码错误！";
                }

                DialogResult result = new DialogResult(ButtonResult.OK);
                result.Parameters.Add("user", user);
                RequestClose.Invoke(result);
            }
            catch (Exception ex)
            {
                ErrorInfo = ex.Message;
            }
        }
    }
}
